package com.goodfox.web.generic.provide.taglib;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.springframework.security.access.ConfigAttribute;

import com.goodfox.web.generic.account.entity.Account;
import com.goodfox.web.generic.authority.filter.SecurityMetadataSourceImpl;
import com.goodfox.web.generic.role.entity.Role;

public class PowerTag extends TagSupport {
	
	private String openUrl="";
	
	public String getOpenUrl() {
		return openUrl;
	}

	public void setOpenUrl(String openUrl) {
		this.openUrl = openUrl;
	}

	/**
	 * 标签开始时写入页面信息
	 */
	public int doStartTag() throws JspException {
		HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
		Account loginAccount=(Account)request.getSession().getAttribute("loginAccount");
		String sDiv="";
		Map<String, Collection<ConfigAttribute>> powerMap=SecurityMetadataSourceImpl.resourcesMap;
		boolean isAuthority=false;
		Collection<ConfigAttribute> configList=powerMap.get(openUrl);
		if(configList!=null){
			for(ConfigAttribute config:configList){
				if(loginAccount!=null){
					if(loginAccount.getRole().getRolePower().equals(config.getAttribute())){
						isAuthority=true;
						break;
					}
				}
			}
		}
		if(isAuthority){
			sDiv="<span>";
		}else{
			sDiv="<span style='display:none;'>";
		}
		output(sDiv);
		return (EVAL_BODY_INCLUDE);
	}
	
	/**
	 * 标签结束时写入页面信息
	 */
	public int doEndTag() throws JspException {
		output("</span>");
		return (EVAL_PAGE);
	}
	
	/**
	 * 将字符串写入页面
	 * @param str 目标字符串
	 * @throws JspException
	 */
	private void output(String str) throws JspException {
		HttpServletResponse response=(HttpServletResponse)pageContext.getResponse();
		JspWriter writer = pageContext.getOut();
		try {
			writer.print(str);
		} catch (IOException e) {
			throw new JspException("FrameTag error");
		}

	}
}
